/**
 * OWASP GoatDroid Project
 * 
 * This file is part of the Open Web Application Security Project (OWASP)
 * GoatDroid project. For details, please see
 * https://www.owasp.org/index.php/Projects/OWASP_GoatDroid_Project
 *
 * Copyright (c) 2011 - The OWASP Foundation
 * 
 * GoatDroid is published by OWASP under the GPLv3 license. You should read and accept the
 * LICENSE before you use, modify, and/or redistribute this software.
 * 
 * @author Jack Mannino, nVisium Security (https://www.nvisiumsecurity.com)
 * @created 2011
 */
package org.owasp.goatdroid.fourgoats.webservice.register;

import java.sql.SQLException;
import java.util.ArrayList;
import org.owasp.goatdroid.fourgoats.webservice.Constants;
import org.owasp.goatdroid.fourgoats.webservice.validators.Validators;

public class RegisterImpl {

	static public RegisterBean registerUser(String firstName, String lastName,
			String userName, String password) {

		RegisterBean bean = new RegisterBean();
		ArrayList<String> errors = Validators.validateRegistrationFields(
				firstName, lastName, userName, password);

		if (errors.size() == 0) {
			RegisterDAO dao;
			try {
				dao = new RegisterDAO();
				// if the user exists, we set an error and don't insert
				if (dao.doesUserExist(userName)) {
					errors.add(Constants.USERNAME_ALREADY_EXISTS);
					dao.closeConnection();
				}
				// if the user doesn't exist, we insert
				else {
					dao.insertNewUser(firstName, lastName, userName, password);
					bean.setSuccess(true);
					dao.closeConnection();
					return bean;
				}
			} catch (InstantiationException e) {
				errors.add(Constants.UNEXPECTED_ERROR);
			} catch (IllegalAccessException e) {
				errors.add(Constants.UNEXPECTED_ERROR);
			} catch (ClassNotFoundException e) {
				errors.add(Constants.UNEXPECTED_ERROR);
			} catch (SQLException e) {
				errors.add(Constants.UNEXPECTED_ERROR);
			}
		}
		bean.setErrors(errors);
		bean.setSuccess(false);
		return bean;
	}
}
